//
//  RiskAppraiseViewC.swift
//  HengYouCai
//
//  Created by lwj on 2017/12/26.
//  Copyright © 2017年 lwj. All rights reserved.
//

import UIKit

/// 答案 分数 model
class AnswerScoreModel: BaseObject {
    
    /// 答案
    var questionAnswer = ""
    
    /// 分数
    var questionScore = ""
    
    /// 选中
    var questionIsSelector = false

}
class RiskAppraiseCell: UITableViewCell {
    
    override func layoutSubviews() {
        
    }
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        
        
        self.contentView.addSubview(self.title)
        title.translatesAutoresizingMaskIntoConstraints =  false

        self.contentView.addConstraint(NSLayoutConstraint(item: title, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier: 1.0, constant: 15))
        self.contentView.addConstraint(NSLayoutConstraint(item: title, attribute: .leading, relatedBy: .equal, toItem: self.contentView, attribute: .leading, multiplier: 1.0, constant: 22))
        self.contentView.addConstraint(NSLayoutConstraint(item: title, attribute: .bottom, relatedBy: .equal, toItem: self.contentView, attribute: .bottom, multiplier: 1.0, constant: -15))
        self.contentView.addConstraint(NSLayoutConstraint(item: title, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1.0, constant: -40))
        self.contentView.addSubview(rightImg)
        _ = rightImg.sd_layout()
            .rightSpaceToView(self.contentView,22)?
            .centerYEqualToView(self.title)?
            .widthIs(15)?
            .heightIs(15)
        
    }
    lazy var title: UILabel = {
        let temp = UILabel()
        temp.font = Font_WL(15)
        temp.textColor = Normal_666Color
        temp.textAlignment = .left
        temp.numberOfLines = 0
        temp.sizeToFit()
        return temp
    }()
    
    lazy var rightImg: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "Risk_circle01"))
    
        return temp
        
    }()
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class RiskAppraiseViewC: BaseViewController,UITableViewDelegate,UITableViewDataSource {
   
    /// mytableView的代理协议
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if questionArr.count>0 {
            return questionArr[currentQuestion-1].count

        }else{
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as? RiskAppraiseCell
        if (cell == nil) {
            cell = RiskAppraiseCell(style: .default, reuseIdentifier: "cellID")
        }
        let answerAndScoreModel = questionArr[currentQuestion-1][indexPath.row]

        cell?.title.text = answerAndScoreModel.questionAnswer
        cell?.rightImg.image =  answerAndScoreModel.questionIsSelector ? UIImage(named: "Risk_circle02") : UIImage(named: "Risk_circle01")

        
        return cell!
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        /// 先把所有的选中状态false 再把选中的置为true 用于点击上一题的时候 有选中题
        for model in questionArr[currentQuestion-1] {
            model.questionIsSelector = false
        }
        let answerAndScoreModel = questionArr[currentQuestion-1][indexPath.row]
        let key = String(format: "question%zd",currentQuestion)
        /// 接口参数
        scorceDic[key] = answerAndScoreModel.questionScore
        
        answerAndScoreModel.questionIsSelector = true
        
        tableView.reloadData()

        if currentQuestion < questionTitleArr.count {
            tableView.isUserInteractionEnabled = false
            let cell = tableView.cellForRow(at: indexPath) as! RiskAppraiseCell
            cell.rightImg.image = UIImage(named: "Risk_circle02")
            self.perform(#selector(nextQuestion(_:)), with: nil, afterDelay: 0.4)

        }else{
            /// 最后一题
            canSubmit = true
            bottomBtn.isEnabled = true
            bottomBtn.backgroundColor = Normal_RedColor
        }
    }

    
    var myTableView : UITableView?
    
    /// 左右边距
    var leftOrRightMargin : CGFloat = 22.0
   
    /// 所有的数据源
    var estimateModel : EstimateQuestionModel?
    
    /// 当前展示的问题是第几个问题
    var currentQuestion : Int = 1
 
    /// 答题结果
    var scorceDic = ["question1":""]
    
    /// 处理过的数据源数组
    var questionArr = [[AnswerScoreModel]]()
    
    /// 问题题目数组
    var questionTitleArr = Array<String>()
    /// 提交按钮可以点击
    var canSubmit = false
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Normal_458Color
        
        clearStackSameVC()
        barButtonItem()
        initMytableView()
        getQuestionList()
    }
    /// 返回键与一键默认
    func barButtonItem() {
        self.navigationItem.title = "风险测评"

        weak var weakSelf = self
        // 一键默认
        let rightBtn = UIButton(type: UIButtonType.custom)
        rightBtn.setTitle("一键默认", for: .normal)
        rightBtn.contentHorizontalAlignment = .right
        rightBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -5)
        rightBtn.setTitleColor(Normal_333Color, for: .normal)
        rightBtn.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        rightBtn.titleLabel?.textAlignment = .right
        rightBtn.titleLabel?.font = Font_WL(14)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        rightBtn.reactive.controlEvents(.touchUpInside).observeValues { (btn) in
            //
            self.oneKeyDefault()
        }
        // 返回键
        let leftBtn = UIButton(type: UIButtonType.custom)
        leftBtn.setImage(UIImage(named: "back"), for: .normal)
        leftBtn.contentHorizontalAlignment = .left
        leftBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0)
        leftBtn.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        leftBtn.reactive.controlEvents(.touchUpInside).observeValues { (btn) in
            // 只要数据请求成功才可展示
            if weakSelf?.estimateModel != nil {
                RiskAlertView.initWithFrame(self.view.bounds, title: "你的风险测评结果默认为", type: weakSelf?.estimateModel?.max_level, desc: weakSelf?.estimateModel?.max_level_description, otherDesc: "", firstBtn: "继续测评", secondBtn: "确定", firsBlock: {
                    //
                }, seconBlock: {
                    //
                    weakSelf?.oneKeyDefault()
                })
            }else{
                weakSelf?.popTheVC()
            }
            
        }

    }
    /// 配置我的tableView
    func initMytableView() {
        //
        
        let rect = CGRect(x: 15, y: 10+kJcwGetNavHeight(), width: JCWSCREENW - 30, height: JCWSCREENH - 20 - kJcwGetNavHeight())
        
        let bgView = UIView(frame: rect)
        bgView.backgroundColor = UIColor.white
        bgView.layer.cornerRadius = 10
        bgView.clipsToBounds = true
        
        bgView.addSubview(titleLab)

        _ = titleLab.sd_layout()
            .topSpaceToView(bgView,49)?
            .leftSpaceToView(bgView,leftOrRightMargin)?
            .rightSpaceToView(bgView,leftOrRightMargin)?
            .autoHeightRatio(0)
        titleLab.setMaxNumberOfLinesToShow(0)
        
        view.addSubview(bgView)
        
        myTableView = UITableView()
  
        myTableView?.separatorStyle = .none
        
        myTableView?.delegate = self
        
        myTableView?.dataSource = self
        
        myTableView?.tableFooterView = myTableFooterView()
        
        myTableView?.rowHeight = UITableViewAutomaticDimension
        myTableView?.estimatedRowHeight = 50
        
        bgView.addSubview(myTableView!)
        
        _ = myTableView?.sd_layout().topSpaceToView(titleLab,20)?.leftSpaceToView(bgView,0)?.rightSpaceToView(bgView,0)?.bottomSpaceToView(bgView,0)
    }
    
    /// 进度条 等
    ///
    /// - Returns: footerView
    func myTableFooterView() -> UIView  {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 200))
        
        
        footerView.addSubview(progressView)
        

        /// 上一题
        footerView.addSubview(lastQuestionBtn)
        
        _ = lastQuestionBtn.sd_layout()
            .topSpaceToView(progressView,13)?
            .leftEqualToView(progressView)?
            .heightIs(15)?
            .widthIs(45)
        lastQuestionBtn.isHidden = true
        lastQuestionBtn.addTarget(self, action: #selector(lastQuestion), for: .touchUpInside)
        
       
       
        ///  提交按钮
        footerView.addSubview(bottomBtn)
        _ = bottomBtn.sd_layout()
            .topSpaceToView(progressView,105)?
            .centerXEqualToView(footerView)?
            .heightIs(44)?
            .leftSpaceToView(footerView,47)?
            .rightSpaceToView(footerView,47)
        bottomBtn.addTarget(self, action: #selector(submitQuestion), for: .touchUpInside)
        return footerView
    }
   
    /// 底部btn的标题
    func bottomBtnTitle() {
        
        let totalCount = questionTitleArr.count
        if currentQuestion < totalCount {
            bottomBtn.isEnabled = false
            bottomBtn.backgroundColor = UIColor.white
            let temp = NSMutableAttributedString(string: String(format: "%zd", currentQuestion), attributes: [NSFontAttributeName:Font_WL(25),NSForegroundColorAttributeName:Normal_RedColor])
            
            temp.append(NSAttributedString(string: String(format: "/%zd", totalCount), attributes: [NSFontAttributeName:Font_WL(16),NSForegroundColorAttributeName:Normal_333Color]))
            bottomBtn.setAttributedTitle(temp, for: .normal)
        }else{
            bottomBtn.setAttributedTitle(nil, for: .normal)
            bottomBtn.setTitle("提交", for: .normal)
            bottomBtn.isEnabled = canSubmit
            bottomBtn.setTitleColor(UIColor.white, for: .normal)
            bottomBtn.titleLabel?.font = Font_WL(15)
            bottomBtn.backgroundColor = canSubmit ? Normal_RedColor : Normal_BBBColor
        }
       

    }
    /// 下一题
    func nextQuestion(_ btn : UIButton) {
        currentQuestion = currentQuestion + 1

        self.myTableView?.isUserInteractionEnabled = true
        
        lastQuestionBtn.isHidden = false
        self.myTableView?.reloadData()
        bottomBtnTitle()
        progressView.setProgress(Float(currentQuestion)/Float(questionTitleArr.count), animated: true)
        self.titleLab.text = questionTitleArr[currentQuestion-1]
    }
    /// 上一题
    @objc func lastQuestion() {
        
        currentQuestion = currentQuestion - 1
        if currentQuestion == 1 {
            lastQuestionBtn.isHidden = true

        }
        self.myTableView?.reloadData()
        bottomBtnTitle()
        progressView.setProgress(Float(currentQuestion)/Float(questionTitleArr.count), animated: true)
        self.titleLab.text = questionTitleArr[currentQuestion-1]
    }
    /// 提交 答案
    func submitQuestion() {
        weak var weakSelf = self

        view.showHUDLoading()
        HYCNetService.getEstimateUserLevel(withDict: scorceDic, onSuccess: { (result) in
            //
            weakSelf?.view.hideHUDLoading(0)
            
            
            UserDefaults.standard.set(result?["levelType"], forKey: kUserLevel)
            let riskAssessmentResultVC = JCWRiskAssessmentResultVC()
            riskAssessmentResultVC.typeIndex = Int((result?["levelType"] as! String))!
            weakSelf?.navigationController?.pushViewController(riskAssessmentResultVC, animated: true)
            
        }) { (code, errorMsg) in
            //
            weakSelf?.view.showHUDFailTips(errorMsg, hideDelay: 1.5)
        }
    }
    /// 一键默认
    func oneKeyDefault() {
       
        weak var weakSelf = self
        view.showHUDLoading()
        HYCNetService.getUpdateUserDefaultLevel(onSuccess: { (result) in
            
            guard let dic = result else {
                weakSelf?.view.hideHUDLoading(0)
                return
            }
            let json = JSON(dic)
            
            UserDefaults.standard.set(json["max_type"].intValue, forKey: kUserLevel)
            
            weakSelf?.view.showHUDSuccessTips("测评成功", hideDelay: kHUDHideDelay)
            weakSelf?.perform(#selector(weakSelf?.popTheVC), with: nil, afterDelay: 1.5)
        }) { (code, errorMsg) in
            
            weakSelf?.view.showHUDFailTips(errorMsg, hideDelay: 1.5)
        }
    }
    /// 问题列表获得
    func getQuestionList() {
        
        weak var weakSelf = self
        view.showHUDLoading()
        HYCNetService.getEstimateQuestionList(onSuccess: { (result) in
            //
            weakSelf?.view.hideHUDLoading(0)
            weakSelf?.estimateModel = EstimateQuestionModel.mj_object(withKeyValues: result)
            guard let list = weakSelf?.estimateModel?.estimateQuestionList else{
                return
            }
            /// 处理数据源
            for model in list {
               
                let riskModel = model as! RiskModel
                /// 问题 题目
                weakSelf?.questionTitleArr.append(riskModel.questionContent)
                
                /// 盛放处理过的没有空的数据
                var currentQuestionArr = Array<AnswerScoreModel>()
                if riskModel.answerA.count > 0{
                    
                    /// 如果有值就封装成新的model 放进当前问题数组中
                    let answerAndScoreModel = AnswerScoreModel()

                    answerAndScoreModel.questionAnswer = "A. " + riskModel.answerA
                    answerAndScoreModel.questionScore = riskModel.scoreA
                    currentQuestionArr.append(answerAndScoreModel)
                }
                if riskModel.answerB.count > 0{
                    
                    /// 如果有值就封装成新的model 放进当前问题数组中
                    let answerAndScoreModel = AnswerScoreModel()
                    
                    answerAndScoreModel.questionAnswer = "B. " + riskModel.answerB
                    answerAndScoreModel.questionScore = riskModel.scoreB
                    currentQuestionArr.append(answerAndScoreModel)
                }
                if riskModel.answerC.count > 0{
                    
                    /// 如果有值就封装成新的model 放进当前问题数组中
                    let answerAndScoreModel = AnswerScoreModel()
                    
                    answerAndScoreModel.questionAnswer = "C. " + riskModel.answerC
                    answerAndScoreModel.questionScore = riskModel.scoreC
                    currentQuestionArr.append(answerAndScoreModel)
                }
                if riskModel.answerD.count > 0{
                    
                    /// 如果有值就封装成新的model 放进当前问题数组中
                    let answerAndScoreModel = AnswerScoreModel()
                    
                    answerAndScoreModel.questionAnswer = "D. " + riskModel.answerD
                    answerAndScoreModel.questionScore = riskModel.scoreD
                    currentQuestionArr.append(answerAndScoreModel)
                }
                if riskModel.answerE.count > 0{
                    
                    /// 如果有值就封装成新的model 放进当前问题数组中
                    let answerAndScoreModel = AnswerScoreModel()
                    
                    answerAndScoreModel.questionAnswer = "E. " + riskModel.answerE
                    answerAndScoreModel.questionScore = riskModel.scoreE
                    currentQuestionArr.append(answerAndScoreModel)
                }
                if riskModel.answerF.count > 0{
                    
                    /// 如果有值就封装成新的model 放进当前问题数组中
                    let answerAndScoreModel = AnswerScoreModel()
                    
                    answerAndScoreModel.questionAnswer = "F. " + riskModel.answerF
                    answerAndScoreModel.questionScore = riskModel.scoreF
                    currentQuestionArr.append(answerAndScoreModel)
                }
                
                weakSelf?.questionArr.append(currentQuestionArr)
            }
            weakSelf?.titleLab.text = weakSelf?.questionTitleArr[0]
            weakSelf?.bottomBtnTitle()
            /// 显示进度条 默认是无色
            weakSelf?.progressView.backgroundColor = Normal_CCCColor
            weakSelf?.progressView.setProgress(1/Float((weakSelf?.questionTitleArr.count)!), animated: true)
            weakSelf?.myTableView?.reloadData()
            
        }) { (code, errorMsg) in
            //
            weakSelf?.view.showHUDFailTips(errorMsg, hideDelay: 1.5)
        }
    }
    //清除之前栈中的答题界面和结果界面 或者是 三部曲界面

    func clearStackSameVC(){
        var stackVCArr = self.navigationController?.viewControllers ?? []
        let totalCount: Int = (self.navigationController?.viewControllers.count ?? 1) - 1
        for i in 0 ..< totalCount {
            guard let vc = self.navigationController?.viewControllers[i] else {continue}
//            print(vc,i)
            if vc.isMember(of: RiskAppraiseViewC.self) || vc.isMember(of: JCWRiskAssessmentResultVC.self) || vc.isMember(of: InvestPrepareVC.self) {
                stackVCArr.remove(at: i)
            }
        }
        self.navigationController?.viewControllers = stackVCArr
    }
    /// 问题 题目
    lazy var titleLab: UILabel = {
        let title = UILabel()
        title.textColor = Normal_333Color
        title.text = ""
        title.textAlignment = .left
        return title
    }()
    
    /// 提交 按钮
    lazy var bottomBtn: UIButton = {
        let btn = UIButton(type: UIButtonType.custom)
        btn.layer.cornerRadius = 22
        btn.isEnabled = false
        return btn
    }()
    
    /// 进度条
    lazy var progressView: UIProgressView = {
        let temp = UIProgressView(frame: CGRect(x: 22, y: 48, width: JCWSCREENW-22-22-30, height: 5))
        
        temp.backgroundColor = UIColor.clear
        temp.progress = 0.0
        temp.layer.cornerRadius = 2.5
        temp.clipsToBounds = true
        temp.progressTintColor = Normal_RedColor
        temp.contentMode = .scaleAspectFill
        temp.transform = CGAffineTransform(scaleX: 1, y: 2)
        for subView in temp.subviews {
            subView.layer.cornerRadius = 2.5;
            
            subView.clipsToBounds = true;
        }
        return temp
    }()
    /// 上一题
    lazy var lastQuestionBtn: UIButton = {
        
        let lastQuestion = UIButton(type: UIButtonType.custom)
        lastQuestion.setTitle("上一题", for: .normal)
        lastQuestion.setTitleColor(Normal_RedColor, for: .normal)
        lastQuestion.titleLabel?.font = Font_WL(13)
        return lastQuestion
    }()
}
